package no.sachmuld.methodcombination.examples.reflection.roles.observer;

import no.sachmuld.methodcombination.api.CrosscuttingBehaviour;
import no.sachmuld.methodcombination.api.MethodInvocation;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class ObservableBehaviour extends CrosscuttingBehaviour implements Observable {

    private List<Observer> observers = new ArrayList<>();

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void deleteObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void after(MethodInvocation<Void> methodInvocation) {
        notifyObservers(methodInvocation.getThis());
    }

    private void notifyObservers(Object observable) {
        for (Observer observer : observers) {
            observer.update(observable);
        }
    }
}
